package com.example.testapp.data.repository

import androidx.lifecycle.LiveData
import com.example.testapp.data.AppDatabase
import com.example.testapp.data.entity.Balance
import com.example.testapp.data.entity.BalanceImage
import com.example.testapp.data.entity.BalanceProcessRecord
import java.io.File
import java.time.LocalDateTime

/**
 * 账单数据仓库，负责连接ViewModel与数据源
 */
class BalanceRepository(private val database: AppDatabase) {

    /**
     * 获取所有账单
     */
    fun getAllBalances(): LiveData<List<Balance>> {
        return database.balanceDao().findAllLive()
    }

    /**
     * 根据ID获取账单
     */
    suspend fun getBalanceById(id: Long): Balance? {
        return database.balanceDao().findById(id)
    }

    /**
     * 根据账单ID获取图片列表
     */
    fun getImagesByBalanceId(balanceId: Long): LiveData<List<BalanceImage>> {
        return database.balanceImageDao().findByBalanceIdLive(balanceId)
    }

    /**
     * 根据账单ID获取处理记录列表
     */
    suspend fun getProcessRecordsByBalanceId(balanceId: Long): List<BalanceProcessRecord> {
        return database.balanceProcessRecordDao().findByBalanceId(balanceId)
    }

    /**
     * 保存或更新账单
     */
    suspend fun saveBalance(balance: Balance): Long {
        if (balance.id == 0L) {
            balance.createDate = LocalDateTime.now()
            balance.updateDate = LocalDateTime.now()
            balance.delFlag = 0
            return database.balanceDao().insert(balance)
        } else {
            balance.updateDate = LocalDateTime.now()
            database.balanceDao().update(balance)
            return balance.id
        }
    }

    /**
     * 保存账单图片
     */
    suspend fun saveBalanceImage(balanceImage: BalanceImage): Long {
        if (balanceImage.id == 0L) {
            balanceImage.createDate = LocalDateTime.now()
            balanceImage.updateDate = LocalDateTime.now()
            balanceImage.delFlag = 0
            return database.balanceImageDao().insert(balanceImage)
        } else {
            balanceImage.updateDate = LocalDateTime.now()
            database.balanceImageDao().update(balanceImage)
            return balanceImage.id
        }
    }

    /**
     * 保存处理记录
     */
    suspend fun saveProcessRecord(record: BalanceProcessRecord): Long {
        if (record.id == 0L) {
            record.createDate = LocalDateTime.now()
            record.updateDate = LocalDateTime.now()
            record.delFlag = 0
            return database.balanceProcessRecordDao().insert(record)
        } else {
            record.updateDate = LocalDateTime.now()
            database.balanceProcessRecordDao().update(record)
            return record.id
        }
    }

    /**
     * 删除账单
     */
    suspend fun deleteBalance(balanceId: Long) {
        val now = LocalDateTime.now()
        database.balanceDao().softDelete(balanceId, now)
        database.balanceImageDao().softDeleteByBalanceId(balanceId, now)
        database.balanceProcessRecordDao().softDeleteByBalanceId(balanceId, now)
    }

    /**
     * 处理图片
     */
    suspend fun processImage(file: File, balanceId: Long): Long {
        // 创建图片记录
        val balanceImage = BalanceImage().apply {
            this.balanceId = balanceId
            this.imagePath = file.absolutePath
            this.processed = false
            this.recognitionStatus = BalanceImage.RECOGNITION_STATUS_PENDING
            this.sortOrder = 0
        }
        val imageId = saveBalanceImage(balanceImage)

        // 创建处理记录
        val processRecord = BalanceProcessRecord().apply {
            this.balanceId = balanceId
            this.processType = BalanceProcessRecord.PROCESS_TYPE_OCR
            this.status = BalanceProcessRecord.STATUS_PENDING
            this.retryCount = 0
            this.maxRetryCount = 3
        }
        saveProcessRecord(processRecord)

        // 更新账单状态
        val balance = getBalanceById(balanceId)
        balance?.let {
            it.status = Balance.STATUS_PROCESSING
            saveBalance(it)
        }
        
        return imageId
    }
}